// Package application
// @Title application[简述该包的主要作用]
// @Description
// @Author  cnHuaShao
// @since v0.0.1
// @Version v1.0.0
// @Date 2024/4/22 23:41
// @Update 2024/4/22 23:41
package application

import (
	"FinancialManagement/src/base/baselog"
	baseUtil "FinancialManagement/src/base/util"
	"FinancialManagement/src/business/user"
	"encoding/base64"

	"github.com/go-oauth2/oauth2/v4/errors"
)

// LoginUser
// @Description: 用户登录接口，认证服务端业务接口
// @param c
func LoginUser(username string, password string) (userID string, err error) {
	if username == "" || password == "" {
		return "", errors.New("请求参数缺失，请确认")
	}
	baselog.Logger.Info(username)
	baselog.Logger.Info(password)
	// 1、账号密码解密
	/*err = decryptUser(&username, &password)
	if err != nil {
		return userID, err
	}*/
	// 2、账号密码验证
	userID, err = passwordAuthorizationHandler(username, password)
	if err != nil {
		return
	}
	return
}

// decryptUser
// @Description: 解密用户账号密码信息
// @param username
// @param password
// @return error
func decryptUser(username, password *string) error {
	// 解密账号
	decodeString, err := base64.StdEncoding.DecodeString(*username)
	if err != nil {
		return errors.ErrInvalidRequest
	}
	// 解密JSON字符串
	*username, err = baseUtil.RSA_DecryptLong(decodeString)
	if err != nil {
		return errors.ErrInvalidRequest
	}
	// 对比密码有效性
	pwdString, err := base64.StdEncoding.DecodeString(*password)
	if err != nil {
		return errors.ErrInvalidRequest
	}
	*password, err = baseUtil.RSA_DecryptLong(pwdString)
	if err != nil {
		return errors.ErrInvalidRequest
	}
	return nil
}

// passwordAuthorizationHandler
// @Description: 自定义账号密码验证逻辑
// @param username
// @param password
// @return error
func passwordAuthorizationHandler(username, password string) (string, error) {
	// 账号密码验证机制
	// 依据账号进行获取用户信息
	userInfo, err := user.ReadUserByID(username)
	if err != nil {
		return "", err
	}
	// 将用户输入的密码进行加密
	newPwd := baseUtil.MD5(password)
	baselog.Logger.Info(newPwd)
	// 进行对比密码是否有效
	if userInfo.Cipher == newPwd {
		// 返回登录成功的用户编号
		return userInfo.Account, nil
	} else {
		return "", errors.ErrAccessDenied
	}
}
